package com.pay.demo.squirrel;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: demo
 * @description: 折扣退款状态机上下文
 * @author: guoxh
 * @create: 2019-04-04 11:00
 **/
public class DiscountRefundStateMachineContext {

    private Long currentInstanceId;
    private Map<Long, Object> currentInstance;

    public DiscountRefundStateMachineContext(Long instanceId, Object instance) {
        this.currentInstanceId = instanceId;
        currentInstance = new HashMap<>();
        this.currentInstance.put(instanceId, instance);
    }

    private static ThreadLocal<DiscountRefundStateMachineContext> contextContainer = new ThreadLocal<DiscountRefundStateMachineContext>() {
    };

    public static DiscountRefundStateMachineContext getInstance(Long instanceId, Object instance) {
        DiscountRefundStateMachineContext discountRefundStateMachineContext = contextContainer.get();
        if (discountRefundStateMachineContext == null) {
            discountRefundStateMachineContext = new DiscountRefundStateMachineContext(instanceId, instance);
            contextContainer.set(discountRefundStateMachineContext);
        } else {
            discountRefundStateMachineContext.currentInstanceId = instanceId;
            discountRefundStateMachineContext.currentInstance.put(instanceId, instance);
        }
        return discountRefundStateMachineContext;
    }

    public Long currentInstanceId() {
        return contextContainer.get() != null ? contextContainer.get().currentInstanceId : null;
    }

    public <T> T currentInstance(Long instanceId) {
        return contextContainer.get() != null ? (T) contextContainer.get().currentInstance.get(instanceId) : null;
    }

}
